Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.
Example:
1 2 3 4 5 6 7 8 9 10 11 12
Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3 Output: [3,3,5,5,6,7] Explanation:
/* * @lc app=leetcode id=239 lang=java * * [239] Sliding Window Maximum */ class Solution { public static int[] maxSlidingWindow(int[] nums, int k) { if (nums.length <= 0) { return nums; }
Deque<Integer> window = new ArrayDeque<>();// 用于储存窗口的下标 int[] res = new int[nums.length - k + 1]; // 从左边开始前进 for (int i = 0; i < nums.length; i++) { //1.窗口界限 2.窗口左边最大的剔除
// 1 if (!window.isEmpty() && window.peek() <= i - k) { window.pollFirst(); }